<!--单位设置-->
<template>
  <div id="unit" class="app-container ">

    <div class="filter-container" style="padding:15px 10px">
      <el-button type="primary" plain @click="handleCreateUnit">新增机构</el-button>
      <template v-if="currentSelectedOrg.id && currentSelectedOrg.type===1 && !currentSelectedOrg.invitationCode">
        <el-button type="primary" plain @click="handleInvitationCode">邀请码</el-button>
      </template>
      <template v-if="currentSelectedOrg.id">
        <el-button type="primary" plain @click="handleCreateDept">新增部门</el-button>
        <el-button type="primary" plain @click="handleUpdate">修改</el-button>
        <el-button v-if="currentSelectedOrg.pid!=='0'" type="primary" plain @click="handleAdjust">调整</el-button>
        <el-button v-if="currentSelectedOrg.pid==='0'" type="danger" plain @click="handleDissolution">解散企业</el-button>
        <el-button v-if="currentSelectedOrg.pid!=='0'" type="danger" plain @click="handleRemove">删除</el-button>
      </template>
      <!--<el-button plain>上移</el-button>
      <el-button plain>下移</el-button>-->
    </div>
    <div class="flex-row" style="flex:1;overflow:hidden">
      <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:280px">
        <unit-tree ref="unitTree" :show-options="true" @selectedOrg="selectedOrg" />
      </div>
      <div class="conmmon-container-main flex-main">
        <el-tabs v-model="currentMode" class="common-tabs" @tab-click="handleTabClick">
          <el-tab-pane label="部门人员" name="userList" />
          <el-tab-pane label="部门信息" name="orgInfo" />
        </el-tabs>
        <div class="table-container flex-main">
          <template v-if="currentMode==='userList'">
            <template v-if="currentSelectedOrg.id">
              <div class="table-container-header">
                <table-toolbar :create="false" :remove="false" @refresh="fetchUserData">
                  <template>
                    <el-button type="primary" icon="el-icon-plus" plain @click="handleAddUser">添加人员</el-button>
                    <el-button type="danger" icon="el-icon-delete" plain @click="handleRemoveUser">移除人员</el-button>
                    <user-list-selector
                      icon="el-icon-setting"
                      text="设置负责人"
                      style="margin-left: 10px;"
                      :org-id="currentSelectedOrg.id"
                      @selectUser="handleSetcharge" />
                  </template>
                </table-toolbar>
              </div>
              <el-table
                ref="multipleTable"
                :data="userList"
                header-cell-class-name="table-header"
                fit
                height="100%"
                highlight-current-row
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column :show-overflow-tooltip="true" label="头像" prop="avatar" width="70" align="center">
                  <template slot-scope="scope">
                    <img :src="common.getFileView(scope.row.avatar)" class="common-round-image-32" data-default="avatar" @error="handleImageError">
                  </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" label="真实姓名" prop="realName" width="100" />
                <el-table-column label="性别" prop="gender" width="100" align="center">
                  <template slot-scope="scope">{{ scope.row.gender==1 ?'男': scope.row.gender==2 ? '女' : '保密' }}</template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" label="手机" prop="mobile" width="110" />
                <el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email" width="150" />
                <el-table-column label="负责人" width="100" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <template v-if="currentSelectedOrg.chargeInfo">
                      <span v-if="currentSelectedOrg.chargeInfo.split(':')[0]===scope.row.id" class="color-primary">是</span>
                      <span v-else class="common-cursor color-danger" @click="currentMode='orgInfo'">去修改</span>
                    </template>
                    <span v-else class="common-cursor color-danger" @click="currentMode='orgInfo'">去设置</span>
                  </template>
                </el-table-column>
                <el-table-column label="直属部门" min-width="280" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.organizationUsers" :key="item.organizationId" :class="item.organizationType===1?'color-primary':'color-default'">  {{ item._fullOrgName }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="userOrgJob" width="150" label="部门任职" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.organizationUsers" :key="item.organizationId" :class="item.organizationType===1?'color-primary':'color-default'">  {{ item.userOrgJob?item.userOrgJob:'-' }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="userOrgPhone" width="150" label="办公电话" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.organizationUsers" :key="item.organizationId" :class="item.organizationType===1?'color-primary':'color-default'">  {{ item.userOrgPhone?item.userOrgPhone:'-' }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="addTime" width="150" sortable label="排序">
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.organizationUsers" :key="item.organizationId" :class="item.organizationType===1?'color-primary':'color-default'">  {{ item.userOrgOrder }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="addTime" width="150" sortable label="加入时间">
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.organizationUsers" :key="item.organizationId" :class="item.organizationType===1?'color-primary':'color-default'">  {{ item.addTime | formatDate('yyyy-MM-dd hh:mm:ss') }} </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="60">
                  <template slot-scope="scope">
                    <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdateUser(scope.row)" />
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination_handler">
                <pagination v-show="userTotal>0" :total="userTotal" :page.sync="listUserQuery.page" :limit.sync="listUserQuery.limit" @pagination="fetchUserData" />
              </div>
            </template>
            <el-empty v-if="!currentSelectedOrg.id" description="暂无组织机构">
              赶快去<span class="color-primary common-cursor" style="margin:auto 5px" @click="handleCreateUnit">新增</span>吧！
            </el-empty>
          </template>
          <template v-if="currentMode==='orgInfo'">
            <el-form
              :model="currentSelectedOrg"
              label-position="right"
              label-width="140px"
              style="margin:20px;overflow: auto;">
              <el-form-item label="邀请员工:">
                <copy-text :content="currentSelectedOrg.invitationCode" position="left" />
                <span v-if="!currentSelectedOrg.invitationCode" class="color-danger common-cursor" @click="handleInvitationCode">点击生成</span>
                <span v-if="currentSelectedOrg.invitationCode" class="color-primary common-cursor" style="margin-left:8px">
                  <copy-text :content="inviteUrl+currentSelectedOrg.invitationCode" position="left" />
                </span>
              </el-form-item>
              <template v-if="currentSelectedOrg.type===1">
                <el-form-item label="标签:">
                  <el-tag>{{ currentSelectedOrg._organizationCategory }}</el-tag>
                  <el-tag v-if="currentSelectedOrg._organizationLevel!=='-'" style="margin-left:8px" type="success">{{ currentSelectedOrg._organizationLevel }}</el-tag>
                  <el-tag v-for="tag in currentSelectedOrg._organizationTags" :key="tag" style="margin-left:8px" type="danger">{{ tag }}</el-tag>
                </el-form-item>
                <el-form-item label="负责人:">
                  {{ currentSelectedOrg.chargeInfo | userSelectorFormat }}
                  <el-tooltip class="item" effect="dark" :content="!currentSelectedOrg.chargeInfo?'设置负责人':'修改负责人'" placement="top">
                    <user-list-selector
                      icon="el-icon-setting"
                      style="margin-left: 10px;"
                      mode="icon"
                      :org-id="currentSelectedOrg.id"
                      @selectUser="handleSetcharge" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="编码:"> {{ currentSelectedOrg.organizationCode }} </el-form-item>
                <el-form-item label="归属:"> ({{ currentSelectedOrg.treeNumber }}){{ currentSelectedOrg._fullOrgName }} </el-form-item>
                <el-form-item label="名称:">{{ currentSelectedOrg.organizationName }}</el-form-item>
                <el-form-item label="排序:">{{ currentSelectedOrg.sortOrders }}</el-form-item>
                <el-form-item label="统一社会信用代码:">{{ currentSelectedOrg.socialCreditCode }}</el-form-item>
                <el-form-item v-if="currentSelectedOrg.businessLicense" label="营业执照:">
                  <img :src="common.getFileView(currentSelectedOrg.businessLicense)" class="common-cursor" style="width:210px" @click="common.handleFilePreview(currentSelectedOrg.businessLicense)">
                </el-form-item>
                <el-form-item label="地址:">
                  {{ currentSelectedOrg._regionLevel1+currentSelectedOrg._regionLevel2+currentSelectedOrg._regionLevel3+currentSelectedOrg._regionLevel4 }}{{ currentSelectedOrg.address }}
                  <map-point-selector v-model="currentSelectedOrg.latlng" mode="show" />
                </el-form-item>
                <el-form-item label="电话:">{{ currentSelectedOrg.phone }}</el-form-item>
                <el-form-item label="传真:">{{ currentSelectedOrg.fax }}</el-form-item>
                <el-form-item label="联系人:">{{ currentSelectedOrg.linkPerson }}</el-form-item>
                <el-form-item label="联系电话:">{{ currentSelectedOrg.linkMobile }}</el-form-item>

                <el-form-item label="单位介绍:">{{ currentSelectedOrg.description }}</el-form-item>
              </template>
              <template v-if="currentSelectedOrg.type===2">
                <el-form-item label="负责人:">
                  {{ currentSelectedOrg.chargeInfo | userSelectorFormat }}
                  <el-tooltip class="item" effect="dark" :content="!currentSelectedOrg.chargeInfo?'设置负责人':'修改负责人'" placement="top">
                    <user-list-selector
                      icon="el-icon-setting"
                      style="margin-left: 10px;"
                      mode="icon"
                      :org-id="currentSelectedOrg.id"
                      @selectUser="handleSetcharge" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="编码:"> {{ currentSelectedOrg.organizationCode }} </el-form-item>
                <el-form-item label="归属:"> ({{ currentSelectedOrg.treeNumber }}){{ currentSelectedOrg._fullOrgName }} </el-form-item>
                <el-form-item label="名称:">{{ currentSelectedOrg.organizationName }}</el-form-item>
                <el-form-item label="排序:">{{ currentSelectedOrg.sortOrders }}</el-form-item>
                <el-form-item label="电话:">{{ currentSelectedOrg.phone }}</el-form-item>
                <el-form-item label="传真:">{{ currentSelectedOrg.fax }}</el-form-item>
                <el-form-item label="联系人:">{{ currentSelectedOrg.linkPerson }}</el-form-item>
                <el-form-item label="联系电话:">{{ currentSelectedOrg.linkMobile }}</el-form-item>
                <el-form-item label="部门介绍:">{{ currentSelectedOrg.description }}</el-form-item>
              </template>
              <el-empty v-if="!currentSelectedOrg.id" description="暂无组织机构">
                赶快去<span class="color-primary common-cursor" style="margin:auto 5px" @click="handleCreateUnit">新增</span>吧！
              </el-empty>
            </el-form>
          </template>
        </div>
      </div>
    </div>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="upmsUserOrganizationRules"
          :model="upmsUserOrganizationRecord"
          label-position="right"
          label-width="120px">
          <el-form-item v-if="currentSelectedOrg" label="用户:" prop="userId">
            {{ upmsUserOrganizationRecord.realName }}
            <el-tooltip v-if="sideBox.status==='create'" class="item" effect="dark" content="请选择用户" placement="top">
              <user-list-selector
                icon="el-icon-setting"
                style="margin-left: 10px;"
                mode="icon"
                :org-id="currentSelectedOrg.selectedOrgId"
                @selectUser="handleSelectedUser" />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="电话:" prop="phone">
            <el-input v-model="upmsUserOrganizationRecord.phone" maxlength="20" show-word-limit placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="岗位:" prop="job">
            <el-input v-model="upmsUserOrganizationRecord.job" maxlength="30" show-word-limit placeholder="请输入员工职位" />
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <template slot="label">
              排序
              <el-tooltip class="item" effect="dark" content="值越大越靠前" placement="bottom">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input-number v-model="upmsUserOrganizationRecord.orders" placeholder="请输入排序" show-word-limit :min="1" :max="9999" style="width:100%" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createOrgUserData():updateOrgUserData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>
<script>
import UnitTree from './UnitTree'
export default {
  components: { UnitTree },

  data() {
    return {
      currentMode: 'userList',
      userList: [],
      userTotal: 0,
      listUserQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        includeChildren: false,
        userName: ''
      },
      multipleSelectionRecords: [],
      currentSelectedOrg: {
        _fullOrgIds: []
      },
      inviteUrl: '',
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      upmsUserOrganizationRecord: {},
      upmsUserOrganizationRules: {
        orders: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }

    }
  },
  watch: {

  },
  created() {
    this.inviteUrl = window.location.protocol + '//' + window.location.host + '/#/invite/'
  },
  mounted() {
  },
  methods: {
    handleTabClick() {

    },
    async fetchUserData() {
      const response = await this.$store.dispatch('userPageV2', this.listUserQuery)
      this.userList = response.records
      this.userTotal = response.total
    },
    selectedOrg(val) {
      this.currentSelectedOrg = val
      this.listUserQuery = {
        ...this.listUserQuery,
        orgId: val.id ? val.id : '-1'
      }
      if (this.currentMode === 'userList') {
        this.fetchUserData()
      }
    },
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    handleCreateUnit() {
      this.$refs.unitTree.handleCreateUnitConfirm()
    },
    handleCreateDept() {
      this.$refs.unitTree.handleCreateDept()
    },
    handleUpdate() {
      this.$refs.unitTree.handleUpdate()
    },
    handleRemove() {
      this.$refs.unitTree.handleRemove()
    },
    handleInvitationCode() {
      this.$refs.unitTree.handleInvitationCode()
    },
    handleAdjust() {
      this.$refs.unitTree.handleAdjust()
    },
    handleDissolution() {
      this.$refs.unitTree.handleDissolution()
    },
    handleInvitationLink() {
      this.$modal.msgWarning('待接入')
    },

    handleAddUser() {
      this.upmsUserOrganizationRecord = {
        organizationId: this.currentSelectedOrg.id,
        orders: 1
      }
      console.log(this.currentSelectedOrg)
      if (this.currentSelectedOrg._fullOrgIds.length > 0) {
        this.currentSelectedOrg = {
          ...this.currentSelectedOrg,
          selectedOrgId: this.currentSelectedOrg._fullOrgIds[0]
        }
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '添加组织用户'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSelectedUser(user) {
      this.$store.dispatch('validateOrganizationUserExist', {
        userId: user.id,
        orgId: this.currentSelectedOrg.id
      }).then(res => {
        if (!res) {
          this.upmsUserOrganizationRecord = {
            ...this.upmsUserOrganizationRecord,
            realName: user.realName,
            userId: user.id
          }
        } else {
          this.$modal.msgWarning(`组织[${this.currentSelectedOrg.organizationName}]已经添加过该用户，无需再次添加`)
        }
      })
    },
    createOrgUserData() {
      if (!this.upmsUserOrganizationRecord.userId) {
        this.$modal.msgWarning('请选择用户')
        return
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('organizationUserSave', this.upmsUserOrganizationRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.fetchUserData()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdateUser(row) {
      this.upmsUserOrganizationRecord = {
        id: row.userOrgId,
        organizationId: row.organizationId,
        phone: row.userOrgPhone,
        job: row.userOrgJob,
        orders: row.userOrgOrder,
        realName: row.realName,
        userId: row.id

      }
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: '编辑组织用户'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateOrgUserData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('organizationUserUpdate', this.upmsUserOrganizationRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.fetchUserData()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    handleRemoveUser() {
      if (this.multipleSelectionRecords.length === 0) {
        this.$modal.msgWarning('请选择要移除人员记录')
        return
      }
      const ids = []
      this.multipleSelectionRecords.forEach((v, i) => {
        ids.push(v.userOrgId)
      })
      this.$confirm('此操作将永久移除记录, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('organizationUserRemove', ids).then(response => {
          this.$modal.msgSuccess('人员移除成功')
          this.fetchUserData()
        }).catch(() => { })
      }).catch(() => { })
    },

    handleSetcharge(user) {
      this.$store.dispatch('organizationSetChargePerson', {
        organizationId: this.listUserQuery.orgId,
        userId: user.id,
        realName: user.realName
      }).then((res) => {
        this.$modal.msgSuccess('负责人设置成功!')
        this.currentSelectedOrg = {
          ...this.currentSelectedOrg,
          chargeInfo: user.id + ':' + user.realName
        }
      }).catch((_) => {})
    }

  }
}
</script>
<style rel="stylesheet/scss" lang="scss" >
  #unit{
    .el-tabs__content{
      height: 0px !important;
      padding: 0px !important;
    }
    .el-tabs--border-card{
      border: 0px;
    }
    .tab-container{
      height: 100%;
      overflow-y: auto;
      background: #fff;
      padding: 30px 36px 10px 36px;
    }
  }
</style>
